package com.sfh.cpc.com;

import android.content.res.AssetManager;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sfh.cpc.com.entity.ECity;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.rx.IResult;
import com.sfh.lib.rx.RetrofitManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Function;


/**
 * 功能描述:城市类型缓存
 *
 * @author SunFeihu 孙飞虎
 * @date 2018/1/18
 */
public class CacheCity {


    public Observable<List<ECity>> queryCity() {
       return  Observable.just(1).map(new Function<Integer, List<ECity>>() {
            @Override
            public List<ECity> apply(Integer integer) throws Exception {
                //2.文件读取
                String json = openFile("address.json");

                if (!TextUtils.isEmpty(json)) {
                    return new Gson().fromJson(json, new TypeToken<List<ECity>>() {
                    }.getType());

                }
                return new ArrayList<>(0);
            }
        });
    }


    /***
     * 读取文件
     * @param fileName
     * @return
     */
    private String openFile(String fileName) {
        AssetManager assetManager = AppCacheManager.getApplication().getAssets();
        StringBuffer json = new StringBuffer(200);
        BufferedReader bufferedReader = null;
        try {
            InputStreamReader reader = new InputStreamReader(assetManager.open(fileName));
            bufferedReader = new BufferedReader(reader);
            String content;
            while (!TextUtils.isEmpty(content = bufferedReader.readLine())) {
                json.append(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
        }
        return json.toString();
    }
}
